package com.haliyoo.adhere.activity;

import java.util.List;

import com.haliyoo.adhere.R;
import com.haliyoo.adhere.bean.UserBean;
import com.haliyoo.adhere.controller.Constants;
import com.haliyoo.adhere.controller.OAuthConstant;
import com.haliyoo.adhere.sqlite.DataHelper4User;
import com.haliyoo.adhere.widget.DialogListener;
import com.haliyoo.adhere.widget.PromptDialog;

import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.AccessToken;
import weibo4android.http.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class LoginActivity extends Activity {
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		finishActivity(requestCode);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
        int flag = getIntent().getIntExtra("flag", 0);  
        if(flag == Constants.EXIT_APPLICATION){  
            finish();  
        }  
        
		super.onResume();
	}

	private static String TAG = "LoginActivity";
	/**
	 * 登录页面中的User是本地缓存的用户信息
	 */
	private static UserBean user = null;
	private EditText userEditText = null;
	private CheckBox rememberUserCheckBox = null;
	private CheckBox autoLoginCheckBox = null;
	private boolean isRememberUser = false;
	private boolean isAutoLogin = false;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        //this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        setContentView(R.layout.login);
        
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
    	Button beginOuathBtn = (Button) findViewById(R.id.BUTTON_LOGIN);
    	userEditText = (EditText) findViewById(R.id.EDIT_TEXT_WEIBO_USER);
    	rememberUserCheckBox = (CheckBox) findViewById(R.id.CHECK_BOX_REMEMBER_USER);
    	autoLoginCheckBox = (CheckBox) findViewById(R.id.CHECK_BOX_AUTO_LOGIN);
    	
    	/// 使用户名编辑框获得焦点
    	userEditText.setFocusableInTouchMode(true);
    	userEditText.setFocusable(true);
    	userEditText.requestFocus();
    	
    	/// 填写被记住的用户
    	userEditText.setText(findRemberedUser());
    	
    	///登录按钮事件
    	beginOuathBtn.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick( View v )
            {
            	/// 查找用户信息是否在数据库中存在
            	selectUser();
            	/// 更新用户的状态（是否被记住）
            	user.setIsRemember(isRememberUser);
            	/// 更新用户的状态（是否被自动登录）
            	user.setIsAutoLogin(isAutoLogin);

            	/**
            	 * 点击登录后的处理流程如下：
            	 * 如果该用户名及对应的账户和密码不存在，则切到微博登录界面
            	 * 否则，直接使用账户和密码登录
            	 */
            	if (!loginedBefore(user)){
                	Weibo weibo = OAuthConstant.getInstance().getWeibo();
                	RequestToken requestToken;
    				try {
    					requestToken =weibo.getOAuthRequestToken("weibo4android://HallActivity");
    	    			Uri uri = Uri.parse(requestToken.getAuthenticationURL()+ "&from=AdHere");
    	    			OAuthConstant.getInstance().setRequestToken(requestToken);
    	    			startActivityForResult(new Intent(Intent.ACTION_VIEW, uri), 100);
    				} catch (WeiboException e) {
    					e.printStackTrace();
    				}
    				
    				//finish();
            	}
            	else{
        			/// 保存数据
        			DataHelper4User dbHelper = new DataHelper4User(LoginActivity.this);
    		        dbHelper.update(user);
    		        
            		login(user);
            	}
            }
        } );
    	
    	/// 记住用户名按钮事件
    	rememberUserCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				isRememberUser = isChecked;
				
				resetAutoLoginControl();
				
				Log.i(TAG, "isRememberUser = " + isRememberUser);
			}
		});
    	
    	/// 自动登录按钮事件
    	autoLoginCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub
				isAutoLogin = isChecked;
				
				Log.i(TAG, "isAutoLogin = " + isAutoLogin);
			}
		});
    	
    	resetAutoLoginControl();
    	
    	/// 自动登录处理
    	if (isRememberUser && isAutoLogin) {
        	/// 查找用户信息是否在数据库中存在
        	selectUser();
        	
    		login(user);
    	}
    }
    
    private void resetAutoLoginControl() {

		autoLoginCheckBox.setClickable(isRememberUser);
		if (!isRememberUser) {
			autoLoginCheckBox.setChecked(false);
			isAutoLogin = false;
		}
    }
    /**
     * 从数据库中查找用户（被记住的）
     * @return
     */
    private String findRemberedUser(){
    	DataHelper4User dbHelper = null;
    	List<UserBean>userList = null;
    	
        //获取账号列表
        dbHelper = new DataHelper4User(this);
        userList = dbHelper.selectByIsRemember(true);
        if (userList.isEmpty()){
        	/// 如果历史用户中没有一个用户是需要记住的，则checkbox不选
        	isRememberUser = false;
        	rememberUserCheckBox.setChecked(isRememberUser);
        	isAutoLogin = false;
        	autoLoginCheckBox.setChecked(isAutoLogin);
        	
        	return null;
        }
        else {
            UserBean user = userList.get(0);
        	
        	/// 如果历史用户中有需要记住的用户，则checkbox选中
            isRememberUser = user.getIsRemember();
        	rememberUserCheckBox.setChecked(isRememberUser);
        	isAutoLogin = user.getIsAutoLogin();
        	autoLoginCheckBox.setChecked(isAutoLogin);

            return user.getUser();
        }
    }

    /**
     * 查找用户信息
     */
    private void selectUser(){
    	DataHelper4User dbHelper = null;
    	List<UserBean>userList = null;
    	
        //获取账号列表
        dbHelper = new DataHelper4User(this);
        userList = dbHelper.selectByUser(userEditText.getText().toString());
        if (userList.isEmpty()){
        	LoginActivity.user = new UserBean();
        	LoginActivity.user.setUser(userEditText.getText().toString());
        }
        else {
            UserBean user = userList.get(0);

            LoginActivity.user = user;
        }
    }
    
    /**
     * 判断用户是否曾经登录过
     * @param user 用于判断的用户信息
     * @return 真假值
     */
    public boolean loginedBefore(UserBean user){
    	if (user.getUser() == null || user.getUser().equals("")
        	|| user.getUserId() == 0
    		|| user.getToken() == null || user.getToken().equals("")
    		|| user.getTokenSecret() == null || user.getTokenSecret().equals("")){
			return false;
		}else{
			return true;
		}
    }
    
    /**
     * 获取用户信息
     * @return 用户信息
     */
    public static UserBean getUser() {
    	return user;
    }
    
    /**
     * 登录
     * @param user 用户
     */
    private void login(UserBean user) {
		// TODO Auto-generated method stub

		AccessToken accessToken = new AccessToken(user.getToken(), user.getTokenSecret(), user.getUserId());
		
		/// 切换到HallActivity页面
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		
		bundle.putSerializable("accesToken", accessToken);
		intent.putExtras(bundle);
		intent.putExtra("from", "LoginActivity");
		intent.putExtra("title", getString(R.string.STR_CREATIVE_HALL));
		intent.setClass(LoginActivity.this, HallActivity.class);
		startActivity(intent);
		
		finish();
	}
    
	//完全退出应用
	public void exit(){
		
//		1.5 - 2.1之前下面两行是ok的,2.2之后就不行了，所以不通用
//		ActivityManager am = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
//		am.restartPackage("com.tutor.exit");
		
		Intent intent = new Intent();
		intent.setClass(LoginActivity.this, AdHereActivity.class);
		//这里设置flag还是比较 重要的
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		//发出退出程序指示
		intent.putExtra("flag", Constants.EXIT_APPLICATION);
		startActivity(intent);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			/// 提示是否退出软件
			System.exit(0);
			
			return false;
		}
		
		return super.onKeyDown(keyCode, event);
	}
}
